import { observer, inject } from 'mobx-react';
import './index.less'
import { getAntd,getEcCom,getLabel } from '../../../util/convert';
import WfGroup from '../../../public/wf-group/index';
import WfCircleIcon from '../../../public/wf-circle-icon/index';
import {trim} from '../../../util/public/common';
import { reloadRequestPage } from '../../../util/formUtil';


/**
 * 明细导入
 */

@inject('globalStore', 'importFieldLinkageStore')
@observer
export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            filename: '',
            isShowDemoModal: false,
        }
    }

    componentDidMount(){
        const { importFieldLinkageStore } = this.props;
        const {workflowid} = this.props.globalStore.commonParam;
        importFieldLinkageStore.riggerFieldLinkageCfg({});
        importFieldLinkageStore.riggerFormulaCfg({workflowid:workflowid});
    }

    render() {
        const {Modal, Row, Col, Button, message} = getAntd();
        const {WeaTools, WeaDialog,WeaCheckbox} = getEcCom();
        const warning = Modal.warning;
        const { globalStore,importFieldLinkageStore } = this.props;
        const {JSComplete,commonParam = {}, loading = false, dialogVisible} = globalStore;
        const {filename, isShowDemoModal} = this.state;
        const {workflowid, requestid, ismode, modeid, formid, isbill, nodeid, f_weaver_belongto_userid, f_weaver_belongto_usertype, wfTestStr, workflowname} = commonParam;
        let visible = false;
        if (dialogVisible.has('importWfDetailModal')) {
            visible = dialogVisible.get('importWfDetailModal');
        }
        const downloadTemplate = <a
            onClick={this.downloadTemplate.bind(this, `/api/workflow/reqform/dowloadTemplate?requestid=${requestid}&workflowid=${workflowid}&nodeid=${nodeid}&_t=${new Date().getTime()}`)}
            target="_blank">{`${workflowname}${getLabel(64,'模板')}`}</a>;

        const fieldTriggerCom = (
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@6n82h9`}
                value = { importFieldLinkageStore.isFieldTrigger }
                display = "switch"
                onChange = {(v)=>{
                    const para = {
                        isFieldTrigger : v==='' ? importFieldLinkageStore.isFieldTrigger : v,
                    };
                    importFieldLinkageStore.updateIsFieldTrigger(para);
                }}
                helpfulTip = {getLabel(512580,'明细导入时执行字段联动将直接修改数据库值')}
            />
        );
        const fieldFormulaCom = (
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@191wfn`}
                value = { importFieldLinkageStore.isFormula }
                display = "switch"
                onChange = {(v)=>{
                    const para = {
                        isFormula : v==='' ? importFieldLinkageStore.isFormula : v,
                        workflowid : workflowid,
                    };
                    importFieldLinkageStore.updateIsFormula(para);
                }}
                helpfulTip = {getLabel(514695,'启用后，触发动作为“值改变时”的明细表公式会在导入后执行，注意执行公式后需保存表单数据才会入库。')}
            />
        );
        const downloadTemp = (
            <div className="download-temp">
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@0fuyyu`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ubscpl`} span={10} style={{height: '28px', lineHeight: '28px'}}><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@rggef0`}/>{`${getLabel(28576,'下载模板')}：`}
                    </Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zc57ip`} span={14} style={{height: '28px', lineHeight: '28px'}}
                         className="file-url">{downloadTemplate}</Col>
                </Row>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@habu81`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@t6y2cu`} span={10} style={{height: '28px', lineHeight: '28px'}}><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@mdqutl`}
                        value='2'/>{`${getLabel(16630,'上传Excel')}：`}</Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@txo9np`} span={14}>
                        <a href="javascript:;" className="a-upload">
                            <input type="file" name="excelfile" size="35" onChange={this.doFileChangeEvent}/>{getLabel(125333,'选择文件')}
                        </a>
                        {
                            <span style={{
                                lineHeight: '28px',
                                height: '28px',
                                marginLeft: '15px'
                            }}>{trim(filename).length > 0 ? filename : getLabel(384040,'未选择任何文件')}</span>
                        }
                    </Col>
                </Row>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@712rqa`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@92lgq6`} span={10} style={{height: '28px', lineHeight: '28px'}}><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@gqvi2k`} value='3'/>{`${getLabel(512581,'导入时执行明细表字段联动')}：`}</Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@gug8q1`} span={14} style={{height: '28px', lineHeight: '28px'}} className="file-url">{fieldTriggerCom}</Col>
            </Row>
                {ismode == 2 &&
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@be7cgx`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3zo4uy`} span={10} style={{height: '28px', lineHeight: '28px'}}><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@dq0gt1`} value='4'/>{`${getLabel(514693,'导入时执行明细表公式')}：`}</Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@1haor3`} span={14} style={{height: '28px', lineHeight: '28px'}} className="file-url">{fieldFormulaCom}</Col>
                </Row>
                }
            </div>
        );

        const steps = (
            <div className="steps">
                <ul>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@6ru2j6`} value='1'/>
                        {getLabel(27578,'请先下载')}
                        <span className="template-download-url">{downloadTemplate}</span>
                        {/*
						{'参照'}
						<span className="template-demo" onClick={this.openDemo.bind(this)}>
							<i className="icon-coms-content-o"/>
							{'填写范例'}
							<ImportDetailDemo visible={isShowDemoModal}/>
						</span>*/
                        }
                        {getLabel(386198,'进行填写导入明细内容，第一行为表单明细字段的名称。')}
                    </li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@g3icja`} value='2'/>{getLabel(514843,'上传Excel”中选择填写好的Excel文件，并点击操作菜单中的“明细导入”按钮。')}</li>
                </ul>
            </div>
        );

        const precautions = (
            <div>
                <ul>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@guekyh`} value='1'/>{getLabel(27582,'导入明细数据时会将原有明细内容删除，导入新的模板中内容。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@mzg3ky`} value='2'/>{getLabel(27583,'只有可编辑的字段才能进行导入，如果查看的字段有默认值的会自动加上默认值。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@o2uqeq`} value='3'/>{getLabel(27584,'模板中第一行为表单明细字段名称，从第二行开始导入明细数据。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@vi95yh`} value='4'/>{getLabel(27585,'明细数据之间不能有空行。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@sulll2`} value='5'/>{getLabel(27586,'如果有多个明细时模板中会有多个SHEET，一个明细一个SHEET。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@81t46m`} value='6'/>{getLabel(27587,'数字类型字段不要有特殊格式，例如：科学计数法，千分位，货币符号等。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@2tqlo2`} value='7'/>{getLabel(515445,'浏览类型字段直接输入名称，也可同时输入名称+"##"+主键，例如：ID为20的人员“张三”，可输入“张三”、“##20”或“张三##20”。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@tyk1ck`} value='8'/>{getLabel(27589,'check类型字段输入“1/0”或“是/否”。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@ex20jd`} value='9'/>{getLabel(514546,'下拉框、复选框、单选框类型字段直接输入选项显示名称。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@ru8v1q`} value='10'/>{getLabel(514547,'多选浏览框或复选框填写多个值以英文半角逗号“,”分隔。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@7iga95`} value='11'/>{getLabel(514548,'人力资源字段支持编号导入，填写格式为：workcode_具体编号。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@eysqs3`} value='12'/>{getLabel(514549,'部门字段支持编号导入，填写格式为：deptcode_具体编号。')}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@qq0ahx`} value='13'/>{importFieldLinkageStore.tips13}</li>
                    <li><WfCircleIcon ecId={`${this && this.props && this.props.ecId || ''}_WfCircleIcon@5qo2ml`} value='14'/>{getLabel(515450,'支持行列规则(普通模式和HTML模式)、字段联动，不支持模板模式下的单元格公式计算，不支持属性联动。')}</li>
                </ul>
            </div>
        );

        return (
            <div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@vanu6k`} visible={visible}
                           loadCss={true}
                           initLoadCss={true}
                           parentClassName="wea-import-wf-detail"
                           style={{'width': '871px','height': '500px'}}
                           hasScroll = {true}
                           maskClosable={false}
                           onCancel={this.cancelEvent}
                           icon = {'icon-coms-workflow'}
                           iconBgcolor = {'#0079DE'}
                           title = {getLabel(26255,'明细导入')}
                           buttons={[
                               <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ba8v57@dimport`} type="primary" size="large" disabled={loading}
                                       onClick={this.submitEvent}>{getLabel(26255,'明细导入')}</Button>,
                               <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rmuv9t@close`} type="ghost" size="large" disabled={loading}
                                       onClick={this.cancelEvent}>{getLabel(309,'关闭')}</Button>
                           ]}>
                    <form ref="uploadform" method="post" encType="multipart/form-data">
                        <WfGroup ecId={`${this && this.props && this.props.ecId || ''}_WfGroup@yem50k`} ref={'group1'} title={getLabel(28576,'下载模板')} groupBodyComponent={downloadTemp}/>
                        <input type="hidden" name="requestid" value={requestid}/>
                        <input type="hidden" name="ismode" value={ismode}/>
                        <input type="hidden" name="modeid" value={modeid}/>
                        <input type="hidden" name="formid" value={formid}/>
                        <input type="hidden" name="isbill" value={isbill}/>
                        <input type="hidden" name="nodeid" value={nodeid}/>
                        <input type="hidden" value="save" name="src"/>
                        <input type="hidden" name="isfromE9" value="1"/>
                        <input type="hidden" name="f_weaver_belongto_userid" value={f_weaver_belongto_userid}/>
                        <input type="hidden" name="f_weaver_belongto_usertype" value={f_weaver_belongto_usertype}/>
                        <input type="hidden" name="wfTestStr" value={wfTestStr}/>
                        <input type="hidden" name="isFieldTrigger" value={ importFieldLinkageStore.isFieldTrigger }/>
                    </form>
                    <WfGroup ecId={`${this && this.props && this.props.ecId || ''}_WfGroup@8g8ead`} ref={'group2'} title={getLabel(27577,'操作步骤')} groupBodyComponent={steps}/>
                    <WfGroup ecId={`${this && this.props && this.props.ecId || ''}_WfGroup@sqzhcu`} ref={'group3'} title={getLabel(15736,'使用注意事项')} groupBodyComponent={precautions}/>
                </WeaDialog>

            </div>
        )
    }

    cancelEvent = () => {
        const {controlDialogVisible} = this.props.globalStore;
        controlDialogVisible('importWfDetailModal', false);
        this.refs.group1.setShowGroup(true);
        this.refs.group2.setShowGroup(true);
        this.refs.group3.setShowGroup(true);
        $('.download-temp').find('input[name=excelfile]').val('');
    }

    submitEvent = () => {
        const _this = this;
        const {Modal,message} = getAntd();

        //验证
        const _reg = /^.*\.(?:xls|xlsx)$/i;
        const {filename = '', type = ''} = _this.state;
        if(!_reg.test(filename)){
            message.warning(getLabel(386469,'必须上传.xls格式的文件 ！'), 2);
            return;
        }
        /*
        if (trim(filename).length === 0 || type !== 'application/vnd.ms-excel') {
            message.warning(getLabel(386469,'必须上传.xls格式的文件 ！'), 2);
            return;
        }*/
        const { globalStore, importFieldLinkageStore } = this.props;
        const {commonParam = {}, controlDialogVisible} = globalStore;
        const {requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype, ismode} = commonParam;
        const formData = new FormData(_this.refs.uploadform);
        globalStore.setLoading(true);
        jQuery.ajax({
            url: '/api/workflow/reqform/doImportDetail',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (response) {
                const ___response = JSON.parse(response);
                if (!___response.noRight) {
                    const {message = ''} = ___response;
                    Modal.warning({
                        content: message.replace(/\\n/g, ''),
                        okText: getLabel(826,'确定'),
                        showClose: false,
                        onOk() {
                            globalStore.setLoading(false);
                            controlDialogVisible('importWfDetailModal', false);
                            setTimeout(function () {
                                if (importFieldLinkageStore.isFormula == "1" && ismode == 2) {
                                    reloadRequestPage({requestid, "importDetail": "1"});
                                } else {
                                    reloadRequestPage({requestid});
                                }
                            },500)


                        }
                    });
                } else {
                    globalStore.setLoading(false);
                }
            },
            error: function (returndata) {
                globalStore.setLoading(false);
            }
        });
    }

    doFileChangeEvent = (e) => {
        const fileInfo = e.currentTarget.files[0];
        const {name = '', type = ''} = fileInfo;
        this.setState({filename: name, type: type});
    }

    openDemo() {
        this.setState({isShowDemoModal: true});
    }

    downloadTemplate(url) {
        jQuery('#WfFormFileDownload').attr('src',url);
    }
}
